package com.kylin.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kylin.service.StatService;
import com.kylin.util.RestTemplateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

/**
 * @Description:
 * @Author: zweiwei
 * @Date: 2022-09-17 11:30:20
 * @Version 1.0
 */
@Service
public class StatServiceImpl implements StatService {

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    @Override
    public String getCompletedQuestionsByUserName(String userName) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        String bodyParam = "{\n" +
                "    \"query\": \"\\n    query userQuestionProgress($userSlug: String!) {\\n  userProfileUserQuestionProgress(userSlug: $userSlug) {\\n    numAcceptedQuestions {\\n      difficulty\\n      count\\n    }\\n    numFailedQuestions {\\n      difficulty\\n      count\\n    }\\n    numUntouchedQuestions {\\n      difficulty\\n      count\\n    }\\n  }\\n}\\n    \",\n" +
                "    \"variables\": {\n" +
                "        \"userSlug\": \"" + userName + "\"\n" +
                "    }\n" +
                "}";
        ResponseEntity<String> post = restTemplateUtil.postJson("https://leetcode.cn/graphql/", bodyParam, String.class);
        String response = post.getBody();
        JsonNode jsonNode = objectMapper.readValue(response, JsonNode.class);
        JsonNode userProfileUserQuestionProgress = jsonNode.get("data").get("userProfileUserQuestionProgress");
        JsonNode numAcceptedQuestions = userProfileUserQuestionProgress.get("numAcceptedQuestions");
        int easy = numAcceptedQuestions.get(0).get("count").asInt();
        int medium = numAcceptedQuestions.get(1).get("count").asInt();
        int hard = numAcceptedQuestions.get(2).get("count").asInt();
        return "easy：" + easy + "\n" + "medium：" + medium + "\n" + "hard：" + hard;
    }
}
